package com.xbf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xbf.entity.User;
import com.xbf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUName, user.getUName());
        User existUser = userService.getOne(queryWrapper);

        if (existUser != null) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }

        // 保存用户信息
        boolean success = userService.save(user);
        result.put("success", success);
        result.put("message", success ? "注册成功" : "注册失败");

        // 返回创建的用户ID
        if(success) {
            result.put("uId", user.getUId());
        }

        return result;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestParam String username, @RequestParam String password) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.login(username, password);

        if (user != null) {
            result.put("success", true);
            result.put("message", "登录成功");
            // 返回完整用户对象
            result.put("user", user);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }

    // 获取用户详细信息
    @GetMapping("/details/{id}")
    public Map<String, Object> getUserDetails(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.getById(id);

        if (user != null) {
            result.put("success", true);
            result.put("user", user);

            // 添加额外信息
            result.put("uEmail", user.getUEmail());
            result.put("uPhone", user.getUPhone());
            result.put("uSex", user.getUSex());
            result.put("uBirthday", user.getUBirthday());
        } else {
            result.put("success", false);
            result.put("message", "用户不存在");
        }

        return result;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @PutMapping("/update")
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Integer id) {
        return userService.removeById(id);
    }
}